package easycloud.ecs.web.service;

import java.util.Date;

import javax.inject.Inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import easycloud.ecs.common.domain.User;
import easycloud.ecs.common.domain.User.Role;
import easycloud.ecs.common.repository.UserRepository;

@Service
@Transactional(readOnly = true)
public class UserService {

	private static final Log logger = LogFactory.getLog(UserService.class);

	@Inject
	private UserRepository userRepository;

	public Page<User> findUsers(Pageable pageable) {
		return userRepository.findAll(pageable);
	}

	public User getUser(Integer id) {
		return userRepository.findOne(id);
	}

	public User getUserByEmail(String email) {
		return userRepository.getByEmail(email);
	}

	public boolean isEmailExist(String email) {
		User user = getUserByEmail(email);
		return user != null;
	}

	@Transactional(readOnly = false)
	public void register(User user, Role role) {
		UserService.logger.debug("register: " + user);
		user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword()
				.getBytes()));
		user.setEnabled(true);
		user.setCreateTime(new Date(System.currentTimeMillis()));
		user.setRole(role);

		userRepository.save(user);
	}

	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public void saveUser(User user) {
		userRepository.save(user);
	}

}
